package com.ken.elmboot.controller;

import com.ken.elmboot.bean.Food;
import com.ken.elmboot.common.ElmException;
import com.ken.elmboot.common.Pager;
import com.ken.elmboot.common.Result;
import com.ken.elmboot.service.FoodService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author ken
 */
@RestController
@RequestMapping("/sys/food")
public class FoodController {
    //不写注解会没调用类，导致空指针异常
    @Autowired
    private FoodService foodService;

    private Logger logger = LoggerFactory.getLogger(FoodController.class);

    @RequestMapping("add")
    public Result add(Food food) {
        Result result = new Result();
        try {
            boolean ret = foodService.add(food);
            if (ret) {
                result.setSuccess(Boolean.TRUE);
                result.setMsg("添加食品成功");
            }else {
                result.setMsg("添加食品失败");
            }
        }catch (ElmException e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @RequestMapping("del")
    public Result del(Integer id) {
        Result result = new Result();
        try {
            boolean ret = foodService.deleteById(id);
            if(ret) {
                result.setSuccess(Boolean.TRUE);
                result.setMsg("删除食品成功");
            }else {
                result.setMsg("删除食品失败");
            }
        }catch (ElmException e) {
            result.setMsg("删除食品异常");
        }
        return result;
    }

    @RequestMapping("edit")
    public Result edit(Food food) {
        Result result = new Result();
        try {
            boolean ret = foodService.edit(food);
            if (ret) {
                 result.setSuccess(Boolean.TRUE);
                 result.setMsg("修改食品信息成功");
            }else {
                result.setMsg("修改食品信息失败");
            }
        }catch (ElmException e) {
            result.setMsg("修改食品信息异常");
        }
        return result;
    }

    @RequestMapping("search")
    public Pager<Food> list(@RequestParam(value = "page",defaultValue = "1") Integer page,
                            @RequestParam(value = "size",defaultValue = "10") Integer size) {
        Pager<Food> pager = new Pager<>();
        int total = foodService.findTotal(pager);
        List<Food> list = foodService.findByPager(pager);
        pager.setTotal(total);
        pager.setRows(list);
        return pager;
    }

}
